//
//  MCCreateNewPlanVc.swift
//  MCBodyBuildingPro
//
//  Created by Renlvshijie on 2023/5/19.
//

import UIKit
import RxSwift
import RxCocoa
import SnapKit
import QMUIKit
import ZLPhotoBrowser
import CustomPopOverView
import MMPopupView
import Kingfisher
import SwiftyJSON
import Toast_Swift
import ObjectMapper



class MCCreateNewPlanVc: MCBaseVc {
    let MCCreateTableIdentifier = "MCCreateTableIdentifier"
    
    @IBOutlet weak var createNewTableView: UITableView!
    
    @IBOutlet weak var cancelButton: UIButton!
    let dispose:DisposeBag = DisposeBag()
    
    private var uploadPlanUrlStr:String? = ""
    
    private var createHeaderInfoView:MCCreateHeaderView!
    
    private var actionType:Int = 0
    private var titleStr:String = ""
    private var introduce:String = ""
    private var musicUrl:String = ""
    private var musicId:String = ""
    
    
    private var sectionDataSource:Array<MCCreatePlanCompleteDataActionModel> = [MCCreatePlanCompleteDataActionModel]()
    
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        cancelButton.layoutIfNeeded()
        cancelButton.layer.borderColor = UIColor.qmui_color(withHexString: "E9ECF3")!.cgColor
        cancelButton.layer.borderWidth = 1
        
        
        self.sectionDataSource.append(MCCreatePlanCompleteDataActionModel(JSON: [:])!)
        self.view.backgroundColor = UIColor.qmui_color(withHexString: "F7F7F9")
        self.createNewTableView.keyboardDismissMode = .onDrag
        self.createNewTableView.delegate = self
        self.createNewTableView.dataSource = self
        self.createNewTableView.rowHeight = 70
        self.createNewTableView.backgroundColor = .clear
        self.createNewTableView.register(UINib(nibName: "MCCreateNewCell", bundle: Bundle.main), forCellReuseIdentifier: MCCreateTableIdentifier)
        
        let createHeaderView = MCCreateHeaderView.initHeaderView()
        createHeaderView.ower = self
        self.createNewTableView.tableHeaderView = createHeaderView
        self.createHeaderInfoView = createHeaderView
        
        let musicTap = UITapGestureRecognizer(target: self, action: #selector(musicPlayerSelect))
        createHeaderView.musicPlayerView.addGestureRecognizer(musicTap)
        
        
        let addZuInfoTap = UITapGestureRecognizer(target: self, action: #selector(addZuInfoAction))
        createHeaderView.addZuInfoLabel.addGestureRecognizer(addZuInfoTap)
        
        createHeaderView.planURLBtn.rx.tap.subscribe(onNext: { event in
            self.view.endEditing(true)
            let selectPhotoView = [MMItemMake("拍摄",.normal,{event in
                let camera = ZLCustomCamera()
                camera.takeDoneBlock = { [weak self] image,videoUrl in self?.saveImage(image: image, videoUrl: videoUrl)}
                self.showDetailViewController(camera, sender: nil)
            }),MMItemMake("从图库选择",.normal,{ event in
                self.showImagePicker(false)
            })]
            let sheetView = MMSheetView.init(title: "选择", items: selectPhotoView as [Any])
            sheetView?.attachedView = self.view
            sheetView?.attachedView.mm_dimBackgroundBlurEnabled = false
            sheetView?.show()
            
        }).disposed(by: dispose)
        
        createHeaderView.timesBlock = { index in
            self.actionType = index
        }
        
        createHeaderView.titleTF.rx.text.orEmpty.asObservable().subscribe(onNext: { event in
            self.titleStr = event
        }).disposed(by: dispose)
        
        createHeaderView.jieshaoTextView.rx.text.orEmpty.asObservable().subscribe(onNext: { str in
            self.introduce = str
        }).disposed(by: dispose)
        
        
        
    }
    
    
    @objc func musicPlayerSelect() -> Void {
        let musicPlayVc = MCMusicPlayVc.init()
        musicPlayVc.musicPlayInfoLastInfo = {[weak self] (musicInfo:MCMusicRecord) in
            self?.musicUrl = musicInfo.bgmUrl ?? ""
            self?.musicId = musicInfo.id ?? ""
            self?.createHeaderInfoView.musicLabel.text = musicInfo.bgmName ?? ""
        }
        self.navigationController?.pushViewController(musicPlayVc, animated: true)
    }
    
    @objc func addZuInfoAction() -> Void {
        self.sectionDataSource.append(MCCreatePlanCompleteDataActionModel(JSON: [:])!)
        self.createNewTableView.reloadData()
        
    }
    
    
    @IBAction func generatePlanSender(_ sender: UIButton) {
        setCreatePlanData()
    }
    
    
    func setCreatePlanData() -> Void {
        print(self.sectionDataSource)
        NetWorkRequest(MCCreateApi.createPlan(planUrl: self.uploadPlanUrlStr, planNeedTime: 0, planName: self.titleStr, introduce: self.introduce, actionType: self.actionType,planBgm:self.musicUrl,planBgmId:self.musicId,actionPlanDetailList:self.sectionDataSource)) { ResponseModel in
            print(ResponseModel.dataString as String)
            let trainDetailPlanVc = MCTraindetailPlanVc.init()
            trainDetailPlanVc.ids = ResponseModel.dataString 
            self.navigationController?.pushViewController(trainDetailPlanVc, animated: true)
            
        } failureCallback: { ResponseModel in
            self.view.makeToast("网络失败",position: .center)
        }
    }
    
    
    
    //保存图片
    func saveImage(image:UIImage?,videoUrl:URL?) -> Void {
        if let image = image {
            ZLPhotoManager.saveImageToAlbum(image: image) { [weak self] suc, asset in
                if suc, let asset = asset {
                    let resultModel = ZLResultModel(asset: asset, image: image, isEdited: false, index: 0)
                    self?.uploadImage(image: resultModel.image)
                }
            }
        }
    
    }
    
    func showImagePicker(_ preview:Bool) -> Void {
        let minItemSpacing:CGFloat = 2
        let minLinespacing:CGFloat = 2
        
        ZLPhotoUIConfiguration.default().minimumLineSpacing(minItemSpacing).minimumLineSpacing(minLinespacing).columnCountBlock {Int(ceil($0 / (428.0 / 4)))}
        ZLPhotoConfiguration.default().editImageConfiguration.canRedo(true)
        ZLPhotoConfiguration.default().maxSelectCount = 1
        ZLPhotoConfiguration.default().allowSelectGif = false
        ZLPhotoConfiguration.default().allowSelectVideo = false
        ZLPhotoConfiguration.default().canSelectAsset { _ in
            true
        }
        
        let ac = ZLPhotoPreviewSheet(results: nil)
    
        ac.selectImageBlock = { [weak self] results, isOriginal in
           let resultModel = results.first
            self?.uploadImage(image: resultModel?.image)
        }
        
        ac.showPhotoLibrary(sender: self)
        
    }
    
    func uploadImage(image:UIImage?) -> Void {
        NetWorkRequest(MineVM.uploadImage(image: image)) { ResponseModel in
            let upLoadModel = uploadmineModel(JSONString: ResponseModel.dataString)
            if upLoadModel?.link?.isEmpty == false {
                self.uploadPlanUrlStr = upLoadModel?.link
                self.createHeaderInfoView.planURLBtn.kf.setImage(with: URL(string: upLoadModel?.link ?? ""), for: .normal)
            }
         
        } failureCallback: { ResponseModel in
            self.view.makeToast("上传失败",position: .center)
        }
    }
    
    
    
}


extension MCCreateNewPlanVc:UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.sectionDataSource.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.sectionDataSource[section].actionPlanDetailActionList?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 45
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        let action = self.sectionDataSource[section]
        
        if action.breakTime == 0 {
            return 0.1
        }else{
            return 45
        }
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:MCCreateNewCell = tableView.dequeueReusableCell(withIdentifier: MCCreateTableIdentifier, for: indexPath) as! MCCreateNewCell
        let actionPlanList = self.sectionDataSource[indexPath.section].actionPlanDetailActionList
        let actionListModel = actionPlanList?[indexPath.row]
        cell.iconImageView.kf.setImage(with: URL(string:actionListModel?.previewUrl ?? ""))
        cell.iconTitleLabel.text = actionListModel?.zhName
        
        if actionListModel?.actionLabel?.isEmpty == false {
            let ActionArr:Array = (actionListModel?.actionLabel?.components(separatedBy: ",") as [String]?)!
            
            for subView  in cell.LabelLayoutVIew.subviews {
                subView.removeFromSuperview()
            }
            
            for actionLabel:String in ActionArr{
                let paddingLabel = QMUIButton.init()
                paddingLabel.backgroundColor = UIColor.qmui_color(withHexString:"#35DE94")?.withAlphaComponent(0.1)
                paddingLabel.setTitleColor( UIColor.qmui_color(withHexString: "#35DE94"), for: .normal)
                paddingLabel.setTitle(actionLabel, for: .normal)
                paddingLabel.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
                paddingLabel.layer.cornerRadius = 5
                paddingLabel.titleLabel?.font = UIFont(name: "PingFangSC-Regular", size: 10)
                paddingLabel.layer.masksToBounds = true
                cell.LabelLayoutVIew.addSubview(paddingLabel)
            }
        }
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = MCCreateZuHeaderView.initZuHeaderView()
        headerView.numOfLabel.text = "第\(section + 1)组"
        var planCompleteActionModel:MCCreatePlanCompleteDataActionModel = self.sectionDataSource[section]
        
        headerView.MCZuXiuBtn.rx.tap.subscribe(onNext: { event in
            //MCAfterGroupTimeVc
            //MCAfterGroupCapacityVc
            let afterGroupTimeVc = MCAfterGroupTimeVc.init()
            afterGroupTimeVc.groupTimeBlock = { event in
                
                let createCompleteDataModel = self.sectionDataSource[section]
                
//                let planCompleteActionModel = MCCreatePlanCompleteDataActionModel(JSON:["actionPlanDetailActionList":createCompleteDataModel?.actionPlanDetailActionList as Any,"exercistTime":createCompleteDataModel?.exerciseTime ?? 0,"isLast":createCompleteDataModel?.isLast ?? 0,"sort":createCompleteDataModel?.sort ?? 0,"breakTime":Int(event)])
                createCompleteDataModel.breakTime = Int(event)
             
                createCompleteDataModel.exerciseTime = (createCompleteDataModel.exerciseTime ?? 0) + (createCompleteDataModel.breakTime ?? 0)
                
                self.createNewTableView.reloadData()
            }
            self.navigationController?.pushViewController(afterGroupTimeVc, animated: true)
        }).disposed(by: dispose)
        
        headerView.addActionBtn.rx.tap.subscribe(onNext: { event in
            
            let selectActionVc = MCSelectActionVc.init()

            selectActionVc.actionType = self.actionType
            selectActionVc.selectType = section
            if planCompleteActionModel.actionPlanDetailActionList == nil {
                selectActionVc.sortValue = 0
            }else{
                selectActionVc.sortValue = planCompleteActionModel.actionPlanDetailActionList?.count ?? 0
            }
           
            selectActionVc.actionModelBlockInfo = { (_ block:MCCreatePlanaddDataModel?,index) in
                
                let planCompleteActionModel:MCCreatePlanCompleteDataActionModel = self.sectionDataSource[section]

                if self.actionType == 0 {
                    
                    var actionPlanBlock:Array<MCCreatePlanaddDataModel>
                    
                    if planCompleteActionModel.actionPlanDetailActionList == nil {
                        
                        actionPlanBlock = [MCCreatePlanaddDataModel]()
                        
                        actionPlanBlock.append(block!)
                    
                    }else {
                        actionPlanBlock = (planCompleteActionModel.actionPlanDetailActionList)!
                        
                        actionPlanBlock.append(block!)
                    }
                    
                    planCompleteActionModel.sort = index ?? 0
                    planCompleteActionModel.exerciseTime = (block?.actionTime ?? 0) + (planCompleteActionModel.exerciseTime ?? 0)
                    planCompleteActionModel.actionPlanDetailActionList = actionPlanBlock
                    
                    if self.sectionDataSource.count == index {
                        planCompleteActionModel.isLast = 1
                    }else {
                        planCompleteActionModel.isLast = 0
                    }
                    
                }else  {
                   // planCompleteActionModel = MCCreatePlanCompleteDataActionModel(JSON: ["actionPlanDetailActionList":[block?.toJSON()],"breakTime":0,"sort":index ?? 0])
                }
                
                self.createNewTableView.reloadData()
                    
            }

            self.navigationController?.pushViewController(selectActionVc, animated: true)
        }).disposed(by: dispose)
        
        return headerView
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        let action = self.sectionDataSource[section]
        
        let footerView = MCCreateZuFooterView.initFooterView()
        
        
        footerView.numOfTitleLabel.text = "组后休息 \((action.breakTime ?? 0)/60)分钟"
        footerView.deleteFooterZuBtn.rx.tap.subscribe { event in
            
        }.disposed(by: dispose)
        return footerView
        
    }
    
    
}
